package com.zx.dsptuneup_TriMic.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.base.tools.tools.StringUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.zx.dsptuneup_TriMic.Adapter.AddChildAdapter;
import com.zx.dsptuneup_TriMic.Adapter.AddDeviceAdapter;
import com.zx.dsptuneup_TriMic.Adapter.AddDeviceAdapter2;
import com.zx.dsptuneup_TriMic.Base.BaseActivity;
import com.zx.dsptuneup_TriMic.Base.NoScrollViewPager;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.Constant;
import com.zx.dsptuneup_TriMic.Util.ToastUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.bean.ChildDeviceBean;
import com.zx.dsptuneup_TriMic.bean.DeviceBean;
import com.zx.dsptuneup_TriMic.bean.JsonChildBean;
import com.zx.dsptuneup_TriMic.bean.ScanDevBean;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;
import com.zx.dsptuneup_TriMic.widget.ui.EmptyView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 增加设备页面
 */
public class AddNewDevActivity extends BaseActivity {
    @BindView(R.id.selAllTxt)
    TextView selAllTxt;
    @BindView(R.id.scanTxt)
    TextView scanTxt;
    @BindView(R.id.listView)
    ListView contentListView;
    @BindView(R.id.ic_nav)
    TextView cancel;
    @BindView(R.id.ic_title)
    TextView ic_title;
    @BindView(R.id.sure_rl)
    TextView sure;
    @BindView(R.id.inc_empty_view)
    EmptyView mIEmptyView;

    private String currentSelPositionId     = "";
    private String currentSelParentdeviceId = "";
    private int REQUEST_CODE = 10086;

    private boolean isParent = true;
    private static AddDeviceAdapter2 addDeviceAdapter;   // 主设备适配器
    private static AddChildAdapter addChildAdapter;      // 子设备适配器
    private static List<DeviceBean> mdeviceList = new ArrayList<>();   // 设备列表
    private static List<ChildDeviceBean> mChilddeviceList = new ArrayList<>();   // 设备列表
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_dev);
        Intent intent = getIntent();
        isParent = intent.getBooleanExtra(Constant.addDevicesType,true);

        if(isParent){
            currentSelPositionId = intent.getStringExtra(Constant.addDevicesPositionID);
            ic_title.setText("录入主设备");
        }else {
            currentSelParentdeviceId = intent.getStringExtra(Constant.addDevicesID);
            ic_title.setText("录入子设备");
        }
        initUI();
        requestData(isParent);
    }

    // 查找主设备还是子设备
    private void requestData(boolean isParent) {
        if(isParent){
            // 假数据
//            for (int i=0;i<10;i++){
//                DeviceBean deviceBean = new DeviceBean();
//                deviceBean.setMac("14-9B-2F-3D-00-30");
//                deviceBean.setIp("192.168.1.16");
//                if(i<4){
//                    deviceBean.setStatus(1);
//                }else if(i==6 || i==7){
//                    deviceBean.setStatus(2);
//                }else if( i==8 || i == 9){
//                    deviceBean.setStatus(3);
//                }else {
//                    deviceBean.setStatus(4);
//                }
//                mdeviceList.add(deviceBean);
//            }
//            addDeviceAdapter.setGridViewBeanList(mdeviceList);

            NetWorkManager.getInstance().getNetWorkApiService().getParentDevices().compose(AddNewDevActivity.this.<BasicResponse<List<DeviceBean>>>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<BasicResponse<List<DeviceBean>>>() {
                        @Override
                        protected void onSuccess(BasicResponse<List<DeviceBean>> response) {
                            if (response != null) {
                                mdeviceList.clear();
                                mdeviceList = response.getData();
                                addDeviceAdapter.setGridViewBeanList(mdeviceList);
                            }
                        }

                        @Override
                        protected void onFail(BasicResponse<List<DeviceBean>> response) {
                            super.onFail(response);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            super.onError(e);
                        }
                    });
        }else {
            NetWorkManager.getInstance().getNetWorkApiService().getChildDevices().compose(AddNewDevActivity.this.<BasicResponse<List<ChildDeviceBean>>>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new DefaultObserver<BasicResponse<List<ChildDeviceBean>>>() {
                        @Override
                        protected void onSuccess(BasicResponse<List<ChildDeviceBean>> response) {
                            if (response != null) {
                                mChilddeviceList.clear();
                                mChilddeviceList = response.getData();
                                addChildAdapter.setGridViewBeanList(mChilddeviceList);
                            }
                        }

                        @Override
                        protected void onFail(BasicResponse<List<ChildDeviceBean>> response) {
                            super.onFail(response);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            super.onError(e);
                        }
                    });
        }
    }

//    @Override
//    public void setData(AddDeviceAdapter2.ViewHolder viewHolder, int position) {
//        final DeviceBean bean = mdeviceList.get(position);
//
//        viewHolder.name_txt.setText(bean.getDeviceName());
//        viewHolder.adress_txt.setText(bean.getPositionName());
//
//    }

    /**
     * Init ui.
     */
    protected void initUI() {
        // 下面这段代码防止页面随着软键盘弹出上移
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        mIEmptyView.setEmptyTip("暂无数据");
        contentListView.setEmptyView(mIEmptyView);

        scanTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddNewDevActivity.this, CaptureActivity.class);
                startActivityForResult(intent,REQUEST_CODE);
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //  全选按钮点击逻辑
        selAllTxt.setSelected(false);
        selAllTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selAllTxt.setSelected(!selAllTxt.isSelected());
                if(selAllTxt.isSelected()){
                    if(isParent){
                        addDeviceAdapter.sellectAll();
                    }else {
                        addChildAdapter.sellectAll();
                    }
                }else{
                    if(isParent){
                        addDeviceAdapter.cancelSelectAll();
                    }else {
                        addChildAdapter.sellectAll();
                    }
                }
            }
        });

        addDeviceAdapter = new AddDeviceAdapter2(this, mdeviceList);
        addDeviceAdapter.setGridViewBeanList(mdeviceList);

        addChildAdapter = new AddChildAdapter(this, mChilddeviceList);
        addChildAdapter.setGridViewBeanList(mChilddeviceList);

        if(isParent){
            contentListView.setAdapter(addDeviceAdapter);
        }else {
            contentListView.setAdapter(addChildAdapter);
        }

        // 点击确定
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isParent){
                   List<DeviceBean> deviceBeanList = addDeviceAdapter.getSelectedItem();
                   if(deviceBeanList.size()<1){
                       ToastUtil.makeText(AddNewDevActivity.this,"请选择设备!");
                       return;
                   }

                   boolean isFull = true;  // 信息是否齐全
                   for (int i=0;i<deviceBeanList.size();i++){
                       DeviceBean deviceBean = deviceBeanList.get(i);
                       if(StringUtils.isEmpty(deviceBean.getDeviceName()) || StringUtils.isEmpty(deviceBean.getPositionName()) ){
                           isFull = false;
                           break;
                       }
                       deviceBean.setPositionId(currentSelPositionId);
                   }
                   if(!isFull){
                       ToastUtil.makeText(AddNewDevActivity.this,"请补全设备信息!");
                       return;
                   }
                   if(StringUtils.isEmpty(currentSelPositionId)){
                       ToastUtil.makeText(AddNewDevActivity.this,"未选择位置信息!请返回!");
                       return;
                   }


                   mDialog.setMsg("正在添加...");
                   showDialog();

                   String jsonStr =  new Gson().toJson(deviceBeanList);
                   HashMap map = new HashMap();
                   // 文档更新，下面参数放在list里面传参
//                   map.put("positionId",currentSelPositionId);
                   map.put("list",jsonStr);
                   NetWorkManager.getInstance().getNetWorkApiService().addParrentDevList(map).compose(AddNewDevActivity.this.<BasicResponse<String>>bindToLifecycle())
                           .subscribeOn(Schedulers.io())
                           .observeOn(AndroidSchedulers.mainThread())
                           .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                @Override
                                protected void onSuccess(BasicResponse<String> response) {
                                    hideDialog();
                                    if (response != null) {
                                        ToastUtil.makeText(AddNewDevActivity.this,"添加主设备成功!");
                                        finish();
                                    }
                                }

                                @Override
                                protected void onFail(BasicResponse<String> response) {
                                    super.onFail(response);
                                    hideDialog();
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    super.onError(e);
                                    hideDialog();
                                }
                            });
                }else {
                    // 添加子设备
                    List<ChildDeviceBean> deviceBeanList = addChildAdapter.getSelectedItem();
                    if(deviceBeanList.size()<1){
                        ToastUtil.makeText(AddNewDevActivity.this,"请选择设备!");
                        return;
                    }

                    if(StringUtils.isEmpty(currentSelParentdeviceId)){
                        ToastUtil.makeText(AddNewDevActivity.this,"未选择主设备信息!请返回!");
                        return;
                    }
                    mDialog.setMsg("正在添加...");
                    showDialog();

                    List<JsonChildBean> jsonChildBeanList = new ArrayList<>();
                    for (int i=0;i<deviceBeanList.size();i++){
                        ChildDeviceBean childDeviceBean = deviceBeanList.get(i);

                        JsonChildBean childBean = new JsonChildBean();
                        childBean.setIp(childDeviceBean.getIp());
                        childBean.setMac(childDeviceBean.getMac());
                        childBean.setType(childDeviceBean.getType());
                        jsonChildBeanList.add(childBean);
                    }

                    String jsonStr =  new Gson().toJson(jsonChildBeanList);
                    HashMap map = new HashMap();
                    map.put("deviceId",currentSelParentdeviceId);
                    map.put("list",jsonStr);

                    NetWorkManager.getInstance().getNetWorkApiService().getChildRelation(map).compose(AddNewDevActivity.this.<BasicResponse<String>>bindToLifecycle())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new DefaultObserver<BasicResponse<String>>() {
                                @Override
                                protected void onSuccess(BasicResponse<String> response) {
                                    hideDialog();
                                    if (response != null) {
                                        ToastUtil.makeText(AddNewDevActivity.this,"添加子设备成功!");
                                        finish();
//                                        new Handler().postDelayed(new Runnable() {
//                                            @Override
//                                            public void run() {
//
//
//                                            }
//                                        }, 500);
                                    }
                                }

                                @Override
                                protected void onFail(BasicResponse<String> response) {
                                    super.onFail(response);
                                    hideDialog();
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    super.onError(e);
                                    hideDialog();
                                }
                            });

                }
            }
        });

    }

    /**
     * 二维码扫描结果
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理扫描结果
        if(requestCode==REQUEST_CODE){
            if(null !=data){
                Bundle bundle = data.getExtras();
                if(bundle == null){
                    return;
                }
                if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
                    String result = bundle.getString(CodeUtils.RESULT_STRING);

                    try {
                        Gson gson = new Gson();
                        ScanDevBean scanDevBean = gson.fromJson(result,ScanDevBean.class);
                        boolean scanIsParent = scanDevBean.getType().contains("音频处理器");
                        if(scanIsParent && !isParent ){ // 扫码是主设备,页面逻辑不是主设备，不匹配
                            ToastUtil.makeText(AddNewDevActivity.this,"设备类型不匹配!");
                            return;
                        }
                        if(!scanIsParent && isParent){
                            ToastUtil.makeText(AddNewDevActivity.this,"设备类型不匹配!");
                            return;
                        }
                        // 查重
                        boolean flag = false;
                        if(scanIsParent){
                            for(int i=0;i<mdeviceList.size();i++){
                                DeviceBean deviceBean = mdeviceList.get(i);
                                if(deviceBean.getMac().equals(scanDevBean.getMac())){
                                    flag = true;
                                }
                            }
                        }else {
                            for(int i=0;i<mChilddeviceList.size();i++){
                                ChildDeviceBean childDeviceBean = mChilddeviceList.get(i);
                                if(childDeviceBean.getMac().equals(scanDevBean.getMac())){
                                    flag = true;
                                }
                            }
                        }
                        if(flag){
                            ToastUtil.makeText(AddNewDevActivity.this,"设备已添加!");
                            return;
                        }

                        // 添加进设备列表
                        if(scanIsParent){
                            DeviceBean deviceBean = new DeviceBean();
                            deviceBean.setMac(scanDevBean.getMac());
                            mdeviceList.add(deviceBean);
                            addDeviceAdapter.setGridViewBeanList(mdeviceList);
                        }else {
                            ChildDeviceBean childDeviceBean = new ChildDeviceBean();
                            childDeviceBean.setMac(scanDevBean.getMac());
                            // * 2：吊麦，3：桌麦
                            int type = 0;
                            if(scanDevBean.getType().contains("桌麦")){
                                type = 3;
                            }
                            if(scanDevBean.getType().contains("吊麦")){
                                type = 2;
                            }
                            childDeviceBean.setType(type);
                            mChilddeviceList.add(childDeviceBean);
                            addChildAdapter.setGridViewBeanList(mChilddeviceList);
                        }

//                        ToastUtil.makeText(AddNewDevActivity.this,"当前类型=="+scanDevBean.getType()+" \n当前Mac地址=="+scanDevBean.getMac());
                    }catch (JsonSyntaxException e){
                        ToastUtil.makeText(AddNewDevActivity.this,"二维码类型不支持!");
                    }

                }else if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED){
                    ToastUtil.makeText(AddNewDevActivity.this,"解析二维码失败!");
                }
            }
        }
    }

}
